<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import type { Role } from '#/api';

import { computed, reactive, ref, watch } from 'vue';

import { Form, FormItem, Input, message, Modal, Radio, Textarea } from 'ant-design-vue';

import { addRoleApi, updateRoleApi } from '#/api';
import { prepareCreateData, prepareUpdateData } from '#/utils/form';

interface Props {
  open: boolean;
  roleData?: Role;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:open', 'success']);

const formRef = ref<FormInstance>();
const confirmLoading = ref(false);

// 是否编辑模式
const isEdit = computed(() => !!props.roleData?.id);

// 表单数据
const formData = reactive<Role>({
  id: undefined,
  roleCode: '',
  roleName: '',
  description: '',
  status: 1,
});

// 表单验证规则
const rules = {
  roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
};

// 监听角色数据变化
watch(
  () => props.roleData,
  (newVal) => {
    if (newVal) {
      Object.assign(formData, newVal);
    } else {
      resetForm();
    }
  },
  { immediate: true },
);

// 重置表单
function resetForm() {
  formData.id = undefined;
  formData.roleCode = '';
  formData.roleName = '';
  formData.description = '';
  formData.status = 1;
  formRef.value?.clearValidate();
}

// 确定
async function handleOk() {
  try {
    await formRef.value?.validate();
    confirmLoading.value = true;

    if (isEdit.value) {
      // 编辑：移除审计字段
      await updateRoleApi(prepareUpdateData(formData) as Role);
      message.success('编辑成功');
    } else {
      // 新增：移除审计字段和 id
      await addRoleApi(prepareCreateData(formData) as Role);
      message.success('新增成功');
    }

    emit('success');
    handleCancel();
  } catch (error) {
    // 验证失败或请求失败
    console.error('保存角色失败:', error);
  } finally {
    confirmLoading.value = false;
  }
}

// 取消
function handleCancel() {
  emit('update:open', false);
  resetForm();
}
</script>

<template>
  <Modal
    :open="open"
    :title="isEdit ? '编辑角色' : '新增角色'"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <FormItem label="角色编码" name="roleCode">
        <Input
          v-model:value="formData.roleCode"
          :disabled="isEdit"
          placeholder="请输入角色编码，如：ADMIN"
        />
      </FormItem>

      <FormItem label="角色名称" name="roleName">
        <Input v-model:value="formData.roleName" placeholder="请输入角色名称" />
      </FormItem>

      <FormItem label="角色描述" name="description">
        <Textarea
          v-model:value="formData.description"
          placeholder="请输入角色描述"
          :rows="3"
          :maxlength="200"
          show-count
        />
      </FormItem>

      <FormItem label="状态" name="status">
        <Radio.Group v-model:value="formData.status">
          <Radio :value="1">启用</Radio>
          <Radio :value="0">禁用</Radio>
        </Radio.Group>
      </FormItem>
    </Form>
  </Modal>
</template>
